function MyUtils() {
};

MyUtils.load = function(pos) {
  var bg = document.createElement('div');
  bg.style.position = 'absolute';
  bg.style.left = 0;
  bg.style.top = 0;
  bg.style.width = document.body.offsetWidth + 'px';
  bg.style.height = document.body.offsetHeight + 'px';
  bg.style.background = 'url(image/pop/bw.png) repeat scroll left top transparent';
  bg.style.zIndex = '999999';
  document.body.appendChild(bg);
  var pane = document.createElement('div');
  bg.appendChild(pane);
  pane.style.position = 'absolute';
  pane.style.left = pos[0] + 'px';
  pane.style.top = pos[1] + 'px';
  pane.style.padding = '5px';
  pane.style.border = '1px solid #dddddd';
  pane.style.backgroundColor = '#ffffff';
  var elm = document.createElement('img');
  elm.src = 'image/loading.gif';
  pane.appendChild(elm);
  return bg;
};

MyUtils.getEventCode = function(e) {
  var code = null;
  if (!e) {
    e = window.event;
  }
  if (e) {
    if (e.keyCode) {
      code = e.keyCode;
    } else if (e.which) {
      code = e.which;
    }
  }
  return code;
};

MyUtils.removeChildElements = function(elem) {
  while (elem && elem.firstChild) {
    elem.removeChild(elem.firstChild);
  }
};

MyUtils.removeTableRows = function(table, rowsToKeep) {
  while (table.rows.length > rowsToKeep) {
    table.deleteRow(table.rows.length - 1);
  }
};

MyUtils.findPos = function(elem) {
  var curleft = 0, curtop = 0;
  if (elem.offsetParent) {
    curleft = elem.offsetLeft;
    curtop = elem.offsetTop;
    while ((elem = elem.offsetParent)) {
      curleft += elem.offsetLeft;
      curtop += elem.offsetTop;
    }
  }
  return [ curleft, curtop ];
};

MyUtils.getEvent = function() {
  if (window.parent == window) {
    return window.event || arguments.callee.caller.arguments[0];
  } else {
    return window.parent.event || arguments.callee.caller.arguments[0];
  }
};

MyUtils.xDocSize = function() {
  var b = document.body, e = document.documentElement;
  var esw = 0, eow = 0, bsw = 0, bow = 0, esh = 0, eoh = 0, bsh = 0, boh = 0;
  if (e) {
    esw = e.scrollWidth;
    eow = e.offsetWidth;
    esh = e.scrollHeight;
    eoh = e.offsetHeight;
  }
  if (b) {
    bsw = b.scrollWidth;
    bow = b.offsetWidth;
    bsh = b.scrollHeight;
    boh = b.offsetHeight;
  }
  return {
    w : Math.max(esw, eow, bsw, bow),
    h : Math.max(esh, eoh, bsh, boh)
  };
};

MyUtils.unique = function() {
  var chars = [];
  for (var i = 48, il = 58; i < il; i++) {
    chars[chars.length] = String.fromCharCode(i);
  }
  for (var i = 65, il = 91; i < il; i++) {
    chars[chars.length] = String.fromCharCode(i);
  }
  for (var i = 97, il = 123; i < il; i++) {
    chars[chars.length] = String.fromCharCode(i);
  }
  var unique = '';
  for (var i = 0, il = 16; i < il; i++) {
    unique += chars[parseInt(Math.abs((Math.random() * 100) % chars.length), 10)];
  }
  return unique;
};

MyUtils.cleanDatepicker = function() {
  var old_fn = $.datepicker._updateDatepicker;
  $.datepicker._updateDatepicker = function(inst) {
    old_fn.call(this, inst);
    var buttonPane = $(this).datepicker("widget").find(".ui-datepicker-buttonpane");
      $("<button type='button' class='ui-datepicker-clean ui-state-default ui-priority-primary ui-corner-all'>清空</button>").appendTo(buttonPane).click(function(ev) {
      $.datepicker._clearDate(inst.input);
    }) ;
  }
};
/**
 * Reference: mypopimage.js
 */
MyUtils.imgWithDel = function(div, big, small, delfunc, opts) {
  var table, tr, td, big, small, elm;
  table = document.createElement('table');
  div.appendChild(table);
  tr = table.insertRow(-1);
  td = tr.insertCell(-1);
  td.style.width = opts.width + 'px';
  td.style.height = opts.height + 'px';
  td.style.verticalAlign = 'top';
  new MyPopImage(td, big, small);
  td = tr.insertCell(-1);
  elm = document.createElement('img');
  elm.src = 'libs/pozo/common/assets/delete24.png';
  elm.style.cursor = 'pointer';
  elm.onclick = function() { delfunc(opts); };
  td.style.verticalAlign = 'top';
  td.appendChild(elm);
};

MyUtils.hilight = function(div, string, search) {
  var idx, elm;
  if (string == null || search == null) {
    return;
  }
  while (search != '' && string.toLowerCase().indexOf(search.toLowerCase()) != -1) {
    idx = string.toLowerCase().indexOf(search.toLowerCase());
    div.appendChild(document.createTextNode(string.substr(0, idx)));
    elm = document.createElement('span');
    elm.style.backgroundColor = '#ffff00';
    elm.appendChild(document.createTextNode(string.substr(idx, search.length)));
    div.appendChild(elm);
    string = string.substr(idx + search.length);
  }
  div.appendChild(document.createTextNode(string));
};

MyUtils.hilightLi = function(div, string, search, length) {
  var idx, elm, PRE = '...', POST = '...';
  if (string == null || search == null) {
    return;
  }
  var pane;
  div._string = string
  div.onmouseover = function() {
    var evt = MyUtils.getEvent();
    pane = document.createElement('div');
    document.body.appendChild(pane);
    pane.style.position = 'absolute';
    pane.style.left = evt.clientX + 20 + 'px';
    pane.style.top = evt.clientY - 10 + 'px';
    pane.style.maxWidth = '200px';
    pane.style.border = '1px solid #000000';
    pane.style.backgroundColor = '#ffffff';
    pane.style.padding = '10px';
    pane.appendChild(document.createTextNode(this._string));
  };
  div.onmouseout = function() {
    if (pane) {
      document.body.removeChild(pane);
      pane = null;
    }
  };
  if (string.toLowerCase().indexOf(search.toLowerCase()) != -1 && search.length > length) {
    elm = document.createElement('span');
    elm.style.backgroundColor = '#ffff00';
    elm.appendChild(document.createTextNode(search.substr(0, length) + POST));
    div.appendChild(elm);
    return;
  } else if (string.toLowerCase().indexOf(search.toLowerCase()) == -1 && string.length > length) {
    string = string.substr(start, length) + POST;
    div.appendChild(document.createTextNode(string));
    return;
  } else if (string.toLowerCase().indexOf(search.toLowerCase()) != -1 && string.length > length) {
    var start = string.toLowerCase().indexOf(search.toLowerCase());
    var space = (length - search.length) / 2;
    if (start < space) {
      start = 0;
      PRE = '';
    } else {
      start = start - space;
    }
    string = PRE + string.substr(start, length) + POST;
  }
  while (search != '' && string.toLowerCase().indexOf(search.toLowerCase()) != -1) {
    idx = string.toLowerCase().indexOf(search.toLowerCase());
    div.appendChild(document.createTextNode(string.substr(0, idx)));
    elm = document.createElement('span');
    elm.style.backgroundColor = '#ffff00';
    elm.appendChild(document.createTextNode(string.substr(idx, search.length)));
    div.appendChild(elm);
    string = string.substr(idx + search.length);
  }
  div.appendChild(document.createTextNode(string));
};

MyUtils.formatDate = function(str, lang, noTime) {
  if (str == '0000-00-00 00:00:00') {
    return '-';
  }
  
  var tmp1 = str.split(' ');
  var tmp2 = tmp1[0].split('-');
  var tmp3 = tmp1[1].split(':');
  
  var year, month, day, hour, minute, second;
  year = tmp2[0];
  month = tmp2[1];
  day = tmp2[2];
  hour = tmp3[0];
  minute = tmp3[1];
  second = tmp3[2];
  
  if (lang == 'zh_CN' || lang == 'zh_TW') {
    if (!noTime) {
      return tmp1[0] + ' ' + hour + ':' + minute;
    } else {
      return tmp1[0];
    }
  } else if (lang == 'en') {
    if (!noTime) {
      return day + ' ' + MyUtils.getMonth(month) + ' ' + year.substring(2, year.length) + ', ' + hour + ':' + minute;
    } else {
      return day + ' ' + MyUtils.getMonth(month) + ' ' + year.substring(2, year.length);
    }
  }
  return lang;
};

/**
 * Return all the months
 */
MyUtils.getMonths = function() {
  return ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
};

/**
 * Return the month in words
 */
MyUtils.getMonth = function(n) {
  var m = MyUtils.getMonths();
  return m[n - 1];
};

/**
 * Return all the days
 */
MyUtils.getDays = function(m, y) {
  var result = [];
  if (
    m == 1 ||
    m == 3 ||
    m == 5 ||
    m == 7 ||
    m == 8 ||
    m == 10 ||
    m == 12
  ) {
    for (var i = 1, il = 32; i < il; i++) {
      result[result.length] = i;
    }
  } else if (
    m == 4 ||
    m == 6 ||
    m == 9 ||
    m == 11
  ) {
    for (var i = 1, il = 31; i < il; i++) {
      result[result.length] = i;
    }
  } else if (m == 2) {
    if (y % 4 == 0) {
      for (var i = 1, il = 30; i < il; i++) {
        result[result.length] = i;
      }
    } else {
      for (var i = 1, il = 29; i < il; i++) {
        result[result.length] = i;
      }
    }
  } else {
    for (var i = 1, il = 32; i < il; i++) {
      result[result.length] = i;
    }
  }
  return result;
};


MyUtils.getShortStr = function(str, len) {
  if (!str) {
    return '';
  }
  if (str.length < len) {
    return str;
  }
  
  var idx = str.lastIndexOf('.');
  var ext = str.substr(idx);
  
  if (ext.length > len) {
    return str.substr(0, len) + '...';
  } else {
    var remain = len - ext.length;
    if (remain % 2 != 0) {
      remain -= 1;
    }
    var left = str.substr(0, remain / 2);
    var right = str.substr(idx - remain / 2, remain / 2);
    return left + '...' + right + ext;
  }
};

MyUtils.getShort = function(str, len) {
  if (!str) {
    return '';
  }
  if (str.length < len) {
    return str;
  }
  
  var left = str.substr(0, len);
  return left + '...';
};

MyUtils.txt2span = function(content, tag) {
  var span = document.createElement(tag);
  var str = '';
  for (var i = 0, il = content.length; i < il; i++) {
    if (content.charAt(i) != '\n') {
      str += content.charAt(i);
    } else {
      span.appendChild(document.createTextNode(str));
      span.appendChild(document.createElement('br'));
      str = '';
    }
  }
  span.appendChild(document.createTextNode(str));
  return span
};

/**
 * Sort an array objects by its attribute 'order' 
 */
MyUtils.sortByOrder = function(array) {
  var array2 = [];
  for (var i = 0, il = array.length; i < il; i++) {
    var obj = array[i];
    
    if (array2.length != 0) {
      var is_added = false;
      for (var j = 0, jl = array2.length; j < jl; j++) {
        var obj2 = array2[j];
        if (parseFloat(obj.order, 10) < parseFloat(obj2.order, 10)) {
          array2.splice(j, 0, obj);
          is_added = true;
          j = array2.length;
        }
      }
      if (!is_added) {
        array2[array2.length] = obj;
      }
    } else {
      array2[array2.length] = obj;
    }
  }
  return array2;
};

MyUtils.imgBtn = function(text, imgPath) {
  var table, tr, td, span, elm;
  span = document.createElement('div');
  span.className = 'image_button';
  table = document.createElement('table');
  tr = table.insertRow(-1);
  td = tr.insertCell(-1);
  elm = document.createElement('img');
  elm.src = imgPath;
  td.appendChild(elm);
  td = tr.insertCell(-1);
  td.appendChild(document.createTextNode(text));
  span.appendChild(table);
  return span;
};

MyUtils.alert = function(text, pos, movable) {
  var container, div, popup = new ModulePopupBox();
  container = document.createElement('div');
  div = document.createElement('div');
  container.appendChild(div);
  div.style.textAlign = 'center';
  div.style.padding = '40px 0';
  div.style.fontFamily = 'Trebuchet MS';
  div.style.fontSize = '13px';
  div.appendChild(document.createTextNode(text));
  div = document.createElement('div');
  container.appendChild(div);
  div.style.textAlign = 'center';
  var ok, cancel;
  ok = MyUtils.imgBtn('OK', 'image/ok24.png');
  ok.style.width = '100px';
  ok._obj = this._obj;
  ok.onclick = function() {
    popup._close();
  };
  div.appendChild(ok);
  popup._open(container, { t: 'Warning', width: 300, height: 200, pos: pos, movable: movable });
};

MyUtils.confirm = function(okFunc, cancelFunc, options) {
  var container, div, popup = new ModulePopupBox();
  container = document.createElement('div');
  div = document.createElement('div');
  container.appendChild(div);
  div.style.textAlign = 'center';
  div.style.padding = '40px 0';
  div.style.fontFamily = 'Trebuchet MS';
  div.style.color = '#000';
  div.style.fontSize = '13px';
  div.appendChild(document.createTextNode('Click OK to proceed?'));
  div = document.createElement('div');
  container.appendChild(div);
  div.style.textAlign = 'center';
  var ok, cancel;
  ok = MyUtils.imgBtn('OK', 'image/ok24.png');
  ok.style.width = '100px';
  ok._obj = this._obj;
  ok.onclick = function() {
    popup._close();
    if (okFunc) {
      okFunc(options);
    }
  };
  div.appendChild(ok);
  cancel = MyUtils.imgBtn('Cancel', 'image/cancel24.png');
  cancel.style.width = '100px';
  cancel.style.marginLeft = '5px';
  cancel.onclick = function() {
    popup._close();
    if (cancelFunc) {
      cancelFunc(options);
    }
  };
  div.appendChild(cancel);
  popup._open(container, { t: 'Confirmation', width: ((options && options.width) ? options.width : 400), height: ((options && options.height) ? options.height : 200), pos: ((options && options.pos) ? options.pos : [ document.body.offsetWidth / 2 - 200, MyUtils.findPos(this)[1] ])});
};

MyUtils.email = function(m) {
  var re = /^[a-zA-Z0-9]([a-zA-Z0-9]*[-_.]?[a-zA-Z0-9]+)+@([a-zA-Z0-9]+\.)+[a-zA-Z]{2,}$/;
  if (m == null || m == "") {
    window.alert('Enter a email');
    return false;
  } else if (!re.test(m)) {
    window.alert('Not a proper email');
    return false;
  }
  return true;
};

MyUtils.pluginObj = function(client_id, order, attr1, attr2, attr3, attr4, attr5, attr6, attr7, attr8, file, path1, path2, path3) {
  return {
    track_id: MyUtils.unique(),
    client_id: (client_id) ? client_id : 0,
    order: (order) ? order : 0,
    attr1: (attr1) ? attr1 : '',
    attr2: (attr2) ? attr2 : '',
    attr3: (attr3) ? attr3 : '',
    attr4: (attr4) ? attr4 : '',
    attr5: (attr5) ? attr5 : '',
    attr6: (attr6) ? attr6 : '',
    attr7: (attr7) ? attr7 : '',
    attr8: (attr8) ? attr8 : '',
    file: (file) ? file : '',
    path1: (path1) ? path1 : '',
    path2: (path2) ? path2 : '',
    path3: (path3) ? path3 : ''
  }
};

MyUtils.getSmallSize = function(actual, max) {
  var width = actual[0];
  var height = actual[1];
  var max_width = max[0];
  var max_height = max[1];
  if ((max_width && width > max_width) || (max_height && height > max_height)) {
    var RESIZEWIDTH = false;
    var RESIZEHEIGHT = false;
    if (max_width && width > max_width) {
      width_ratio = max_width / width;
      RESIZEWIDTH = true;
    }
    if (max_height && height > max_height) {
      height_ratio = max_height / height;
      RESIZEHEIGHT = true;
    }
    if (RESIZEWIDTH && RESIZEHEIGHT) {
      if (width_ratio < height_ratio) {
        $ratio = width_ratio;
      } else {
        $ratio = height_ratio;
      }
    } else if (RESIZEWIDTH) {
      $ratio = width_ratio;
    } else if (RESIZEHEIGHT) {
      $ratio = height_ratio;
    }
    return [parseInt(width * $ratio, 10), parseInt(height * $ratio, 10)];
  }
  return actual;
};

MyUtils.hilightArray = function(args1, args2, length) {
  if (args2.length == 0) {
    return "<span>-</span>";
  }
  
  var string = '', searchs = [];
  for (var i in args2) {
    string += args2[i];
    if (i < args2.length - 1) {
      string += ',';
    }
  }
  
  for (var j in args1) {
    if (string.toLowerCase().indexOf(args1[j].toLowerCase()) != -1) {
      var name = args1[j];
      var index = string.toLowerCase().indexOf(args1[j].toLowerCase());
      var str_len = args1[j].length;
      var obj = new Object();
      obj.name = name;
      obj.index = index;
      obj.str_len = str_len;
      searchs.push(obj);
    }
  }
  
  if (searchs.length == 0) {
    if (string.length > length) {
      return "<span>" + string.substr(0, length) + "...</span>";
    } else {
      return "<span>" + string + "</span>";
    }
  }
   
  MyUtils.sort(searchs, ['index']);
  
  var total_length = 0;
  for (var k in searchs) {
    var search = searchs[k];
    total_length = parseInt(total_length) + parseInt(search.str_len);
  }
  
  if (total_length != 0 ) {
    if (total_length == length) {
      var str = MyUtils.arrayToHtml(searchs, string);
    } else if (total_length < length) {
      var str = MyUtils.arrayToHtml(searchs, string);
    } else if (total_length > length) {
      var arrs = [], s_len = 0;
      for (var i in searchs) {
        s_len = parseInt(s_len) + parseInt(searchs[i].str_len);
        if (parseInt(s_len) <= length) {
          arrs.push(searchs[i]);
        }
      }
      if (arrs.length == 0) {
        arrs.push(searchs[0]);
      }
      var str = MyUtils.arrayToHtml(arrs, string);
    }
  }
  
  return str;
};

MyUtils.arrayToHtml = function(searchs, string) {
  var html = "<span>";
  var i = 0;
  while (i < searchs.length) {
    if (searchs[i].index == 0) {
      if (searchs[i+1]) {
        if (parseInt(searchs[i].index) + parseInt(searchs[i].str_len) + parseInt(1) == searchs[i+1].index) {
          html += "<span style='background-color: #ffff00'>" + searchs[i].name + "</span>";
        } else {
          html += "<span style='background-color: #ffff00'>" + searchs[i].name + "</span>...";
        }
      } else {
        if (parseInt(searchs[i].index) + parseInt(searchs[i].str_len) < string.length) {
          html += "<span style='background-color: #ffff00'>" + searchs[i].name + "</span>...";
        } else {
          html += "<span style='background-color: #ffff00'>" + searchs[i].name + "</span>";
        }
      }
    } else {
      if (i == 0) {
        html += "...<span style='background-color: #ffff00'>" + searchs[0].name + "</span>";
      } else {
        if (searchs[i+1]) {
          if (parseInt(searchs[i].index) + parseInt(searchs[i].str_len) + parseInt(1) == searchs[i+1].index) {
            html += "<span style='background-color: #ffff00'>" + searchs[i].name + "</span>";
          } else {
            html += "<span style='background-color: #ffff00'>" + searchs[i].name + "</span>...";
          }
        } else {
          if (parseInt(searchs[i].index) + parseInt(searchs[i].str_len) < string.length) {
            html += "<span style='background-color: #ffff00'>" + searchs[i].name + "</span>...";
          } else {
            html += "<span style='background-color: #ffff00'>" + searchs[i].name + "</span>";
          }
        }
      }
    }
    i++;
  } 
    
  html += '</span>';
  return html;
};

MyUtils.sort = function(arrays, attrs) {
  var func = function(a, b) { var v1 = a, v2 = b;
    for (var i = 0, il = attrs.length; i < il; i++) {
      v1 = v1[attrs[i]];
      v2 = v2[attrs[i]]
    }
    if (!isNaN(v1) && !isNaN(v2)) {
      if (v1 && v2 && parseInt(v1, 10) > parseInt(v2, 10)) {
        return true;
      }
    }
    return false;
  };
  
  arrays.sort(func);
};

MyUtils.trim = function(str) {
  return str.replace(/(^\s*)|(\s*$)/g, "");
};

MyUtils.showDate = function(date_str, type) {
  if (date_str == '0000-00-00 00:00:00') {
    return '';
  }
  var tmp1 = date_str.split(' ');
  var tmp2 = tmp1[0].split('-');
    
  var year, month, day, hour, minute, second;
  year = tmp2[0];
  month = tmp2[1];
  day = tmp2[2];
  
  if (type == 'nyc') {
    if (tmp1[1]) {
      return month + '/' + day + '/' + year + ' ' + tmp1[1];
    } else {
      return month + '/' + day + '/' + year;
    }
  } else {
    if (tmp1[1]) {
      return day + '/' + month + '/' + year + ' ' + tmp1[1];
    } else {
      return day + '/' + month + '/' + year;
    }
  }
}

MyUtils.dateShow = function(sd, type, nosecond, nohours) {
  if (type == 'nyc') {
    if (nohours) {
      return (sd.month + '/' + sd.date + '/' + sd.year);
    } else {
      if (nosecond) {
        return (sd.month + '/' + sd.date + '/' + sd.year + ' ' + sd.hours + ':' + sd.minutes);
      } else {
        return (sd.month + '/' + sd.date + '/' + sd.year + ' ' + sd.hours + ':' + sd.minutes + ':' + sd.seconds);
      }
    }
  } else {
    if (nohours) {
      return (sd.date + '/' + sd.month + '/' + sd.year);
    } else {
      if (nosecond) {
        return (sd.date + '/' + sd.month + '/' + sd.year + ' ' + sd.hours + ':' + sd.minutes);
      } else {
        return (sd.date + '/' + sd.month + '/' + sd.year + ' ' + sd.hours + ':' + sd.minutes + ':' + sd.seconds);
      }
    }
  }
};

MyUtils.daysInMonth = function(month, year) {
  return new Date(year, month, 0).getDate();
}

MyUtils.get_quantity = function(value) {
  var total = 0;
  if (value.indexOf('+') == -1) {
	 total = parseFloat(value, 10); 
  } else {
	var tmps = value.split('+');
	if (tmps.length > 0) {
	  for (var i in tmps) {
		var tmp = tmps[i];
		if (tmp == '' || isNaN(tmp)) {
		  continue;	
		}
		total += parseFloat(tmp, 10);
	  }
	}
  }
  return parseFloat(total, 10).toFixed(2);
}